#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/12/19 9:59
# @Author : ZhengQL

import logging
import os
from common.Path_Handler import PathHandler

class LoggerHandler:
    """
    日志处理类
    """
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(LoggerHandler, cls).__new__(cls)
            cls._instance.init_logger()
        return cls._instance

    def init_logger(self):
        self.logger = logging.getLogger('mylogger')
        self.logger.setLevel(logging.DEBUG)

        log_dir = PathHandler.log_path
        os.makedirs(log_dir, exist_ok=True)
        log_file_path = os.path.join(log_dir, 'mylog.txt')

        try:
            file_handler = logging.FileHandler(log_file_path, encoding='utf-8')
        except Exception as e:
            print(f"Failed to create file handler: {e}")
            return

        console_handler = logging.StreamHandler()

        formatter = logging.Formatter('%(asctime)s - %(filename)s-->line:%(lineno)d] - %(levelname)s - %(message)s')
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)



if __name__ == '__main__':
    logger = LoggerHandler().logger
    logger.debug('debug')
    logger.info('info')
    logger.warning('warning')
    logger.error('error')
